package com.ershui.blog.system.controller;

import com.ershui.blog.config.FilePathConfig;
import com.ershui.blog.system.domain.UpFileResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    public static final Logger log = LoggerFactory.getLogger(com.ershui.blog.system.controller.CommonController.class);

    @Autowired
    private FilePathConfig filePathConfig;


    @PostMapping("/uploadImage")
    @ResponseBody
    public UpFileResult uploadSingleImage(MultipartFile file){
        UpFileResult upFileResult=new UpFileResult();
        try{
            if(file.isEmpty()){
                upFileResult.setErrno(1);
                return upFileResult;
            }
            String fileName=file.getOriginalFilename();
            String fileType=fileName.substring(fileName.lastIndexOf("."),fileName.length());
            String uuidStr=GetUUidStr();
            //文件真实存储路径
            String extraFileName= filePathConfig.getFileOriPath()+"/"+GetDateStr()+"/"+uuidStr+"``"+fileType;
            //映射虚拟路径
            String ormUrl=filePathConfig.getFileOrmPath()+"/"+GetDateStr()+"/"+uuidStr+"``"+fileType;
            File dest=new File(extraFileName);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            upFileResult.setErrno(0);
            List<String> data=new ArrayList<>();
            data.add(extraFileName);

            upFileResult.setUrl(ormUrl);
            upFileResult.setData(data);
        }catch (Exception e){
            e.printStackTrace();
            log.error("文件上传失败："+file.getOriginalFilename());
        }

        return upFileResult;
    }


    /**
     * 获取当前时间串，用于文件存储路径使用
     * @return
     */
    public String GetDateStr(){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
        String dateStr=sdf.format(date);
        return dateStr;
    }

    /**
     * 获取UUID随机串，上传文件使用
     * @return
     */
    public String GetUUidStr(){
        String uuidStr= UUID.randomUUID().toString();
        return uuidStr;
    }
}
